#!/usr/bin/env python3
"""
JPY汇率检测系统启动脚本
适用于开发环境快速启动
"""

import os
import sys
import subprocess
import logging
from pathlib import Path

# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def check_requirements():
    """检查系统要求"""
    logger.info("检查系统要求...")
    
    # 检查Python版本
    if sys.version_info < (3, 11):
        logger.error("需要Python 3.11或更高版本")
        return False
    
    # 检查虚拟环境
    venv_path = Path("venv")
    if not venv_path.exists():
        logger.info("创建虚拟环境...")
        subprocess.run([sys.executable, "-m", "venv", "venv"], check=True)
    
    return True

def install_dependencies():
    """安装依赖"""
    logger.info("安装Python依赖...")
    
    venv_python = Path("venv/bin/python") if os.name != 'nt' else Path("venv/Scripts/python.exe")
    
    if not venv_python.exists():
        logger.error("虚拟环境Python不存在")
        return False
    
    subprocess.run([str(venv_python), "-m", "pip", "install", "--upgrade", "pip"], check=True)
    subprocess.run([str(venv_python), "-m", "pip", "install", "-r", "requirements.txt"], check=True)
    
    return True

def setup_environment():
    """设置环境"""
    logger.info("设置环境...")
    
    # 创建必要的目录
    Path("logs").mkdir(exist_ok=True)
    Path("frontend/dist").mkdir(parents=True, exist_ok=True)
    
    # 检查环境变量文件
    if not Path(".env").exists():
        logger.info("创建环境变量文件...")
        Path(".env").write_text(Path(".env.example").read_text())
        logger.warning("请编辑 .env 文件配置钉钉Webhook等参数")
    
    return True

def build_frontend():
    """构建前端"""
    logger.info("构建前端...")
    
    frontend_dir = Path("frontend")
    if not frontend_dir.exists():
        logger.warning("前端目录不存在，跳过前端构建")
        return True
    
    # 检查Node.js
    try:
        subprocess.run(["node", "--version"], check=True, capture_output=True)
        subprocess.run(["npm", "--version"], check=True, capture_output=True)
    except (subprocess.CalledProcessError, FileNotFoundError):
        logger.warning("Node.js或npm未安装，跳过前端构建")
        return True
    
    # 安装前端依赖并构建
    try:
        subprocess.run(["npm", "install"], cwd=frontend_dir, check=True)
        subprocess.run(["npm", "run", "build"], cwd=frontend_dir, check=True)
        logger.info("前端构建完成")
    except subprocess.CalledProcessError as e:
        logger.error(f"前端构建失败: {e}")
        return False
    
    return True

def start_server():
    """启动服务器"""
    logger.info("启动服务器...")
    
    venv_python = Path("venv/bin/python") if os.name != 'nt' else Path("venv/Scripts/python.exe")
    
    # 设置环境变量
    env = os.environ.copy()
    env["PYTHONPATH"] = str(Path.cwd())
    
    # 启动uvicorn
    cmd = [
        str(venv_python), "-m", "uvicorn",
        "backend.app:app",
        "--host", "0.0.0.0",
        "--port", "8000",
        "--reload"
    ]
    
    logger.info(f"启动命令: {' '.join(cmd)}")
    logger.info("访问地址: http://localhost:8000")
    
    try:
        subprocess.run(cmd, env=env, check=True)
    except KeyboardInterrupt:
        logger.info("服务器已停止")
    except subprocess.CalledProcessError as e:
        logger.error(f"服务器启动失败: {e}")
        return False
    
    return True

def main():
    """主函数"""
    logger.info("🚀 启动JPY汇率检测系统...")
    
    try:
        # 检查系统要求
        if not check_requirements():
            return 1
        
        # 安装依赖
        if not install_dependencies():
            return 1
        
        # 设置环境
        if not setup_environment():
            return 1
        
        # 构建前端
        if not build_frontend():
            return 1
        
        # 启动服务器
        if not start_server():
            return 1
        
        return 0
        
    except Exception as e:
        logger.error(f"启动失败: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())
